/*
 * Copyright 2002-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.security.web.authentication.session;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.core.log.LogMessage;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
import org.springframework.web.util.WebUtils;

/**
 * A base class for performing session fixation protection.
 * 处理会话固定攻击的基类，它是SessionFixationProtectionStrategy和ChangeSessionIdAuthenticationStrategy的父类，用来防御session fixation攻击。
 * 1:session是服务端的一个概念，服务端生成session都会生成一个对应的SessionID,这个SessionId会通过Cookie传递给前端，前端以后发送请求的时候，
 * 都会带上sessionID的参数，服务端看到请求中带了sessionId, 就会根据这个sessionID取出对应的session信息。
 * 2:浏览器的关闭不会导致服务器的session失效，服务端session失效只有两种情况：一是session过期，二是session的invalidate方法，还有就是重启客户端。
 * 3:为什么我们平时觉得浏览器关闭了，session就失效了吗？这是因为浏览器里面的sessionID丢了，所以当浏览器再次访问服务器端的时候，
 * 服务器会重新给浏览器分配一个sessionId ,这个sessionId和之前的那么session对应不上，所以用户就会感觉session失效
 * 4:会话固定（Session fixation）是一种诱骗受害者使用攻击者指定的会话标识（SessionID）的攻击手段。这是攻击者获取合法会话标识的最简单的方法。
 * （让合法用户使用黑客预先设置的sessionID进行登录，从而使Web不再进行生成新的sessionID，从而导致黑客设置的sessionId变成了合法桥梁。）
 * 5:攻击步骤(原理：登录后的sessionId和登录前的SessionId没有变化)：
 * (1).攻击者打开一个登录页面
 * (2).服务端会返回攻击者一个sessionId = 123xyz
 * (3).攻击者发送一个伪装连接并带上sessionId
 * (4).然后正常用户接到后，点击进行登录
 * (5).这时候服务端sessionID=123xyz的session已经存在
 * (6).这时，有了这个sessionID ,攻击者就可以正大光明的访问漏洞系统了。
 * 可参考：https://blog.csdn.net/fd2025/article/details/124490876
 * @author Rob Winch
 * @since 3.2
 */
public abstract class AbstractSessionFixationProtectionStrategy
		implements SessionAuthenticationStrategy, ApplicationEventPublisherAware {

	protected final Log logger = LogFactory.getLog(this.getClass());

	/**
	 * Used for publishing events related to session fixation protection, such as
	 * {@link SessionFixationProtectionEvent}.
	 */
	private ApplicationEventPublisher applicationEventPublisher = new NullEventPublisher();

	/**
	 * If set to {@code true}, a session will always be created, even if one didn't exist
	 * at the start of the request. Defaults to {@code false}.
	 * 如果设置为{@code true}，则总是会创建会话，即使在请求开始时不存在会话。默认为{@code false}。
	 */
	private boolean alwaysCreateSession;

	AbstractSessionFixationProtectionStrategy() {
	}

	/**
	 * Called when a user is newly authenticated.
	 * <p>
	 * If a session already exists, and matches the session Id from the client, a new
	 * session will be created, and the session attributes copied to it (if
	 * {@code migrateSessionAttributes} is set). If the client's requested session Id is
	 * invalid, nothing will be done, since there is no need to change the session Id if
	 * it doesn't match the current session.
	 * <p>
	 * If there is no session, no action is taken unless the {@code alwaysCreateSession}
	 * property is set, in which case a session will be created if one doesn't already
	 * exist.
	 */
	@Override
	public void onAuthentication(Authentication authentication, HttpServletRequest request,
			HttpServletResponse response) {
		// 是否已经有session
		boolean hadSessionAlready = request.getSession(false) != null;
		// 如果没有session，并且不用总是创建session，直接返回，不需要防御session fixation
		if (!hadSessionAlready && !this.alwaysCreateSession) {
			// Session fixation isn't a problem if there's no session
			return;
		}
		// Create new session if necessary
		// 获取session，因为alwaysCreateSession默认为false,到此处说明请求一定存在session
		HttpSession session = request.getSession();
		// 如果已经有session，并且session有效
		if (hadSessionAlready && request.isRequestedSessionIdValid()) {
			// 原来的session id
			String originalSessionId;
			// 新的session id
			String newSessionId;
			// 获取session对应的互斥锁synchonized object
			Object mutex = WebUtils.getSessionMutex(session);
			synchronized (mutex) {
				// We need to migrate to a new session
				// 保存原来的session id
				originalSessionId = session.getId();
				// 调用子类的applySessionFixation方法，执行攻击防御逻辑 这里返回一个session
				session = applySessionFixation(request);
				// 获取新的session id
				newSessionId = session.getId();
			}
			// 如果新的session和老的还是相同，打印告警信息
			if (originalSessionId.equals(newSessionId)) {
				this.logger.warn("Your servlet container did not change the session ID when a new session "
						+ "was created. You will not be adequately protected against session-fixation attacks");
			}
			else {
				if (this.logger.isDebugEnabled()) {
					this.logger.debug(LogMessage.format("Changed session id from %s", originalSessionId));
				}
			}
			// 发布SessionFixationProtectionEvent这个事件
			onSessionChange(originalSessionId, session, authentication);
		}
	}

	/**
	 * Applies session fixation
	 * @param request the {@link HttpServletRequest} to apply session fixation protection
	 * for
	 * @return the new {@link HttpSession} to use. Cannot be null.
	 */
	abstract HttpSession applySessionFixation(HttpServletRequest request);

	/**
	 * Called when the session has been changed and the old attributes have been migrated
	 * to the new session. Only called if a session existed to start with. Allows
	 * subclasses to plug in additional behaviour. *
	 * <p>
	 * The default implementation of this method publishes a
	 * {@link SessionFixationProtectionEvent} to notify the application that the session
	 * ID has changed. If you override this method and still wish these events to be
	 * published, you should call {@code super.onSessionChange()} within your overriding
	 * method.
	 * @param originalSessionId the original session identifier
	 * @param newSession the newly created session
	 * @param auth the token for the newly authenticated principal
	 */
	protected void onSessionChange(String originalSessionId, HttpSession newSession, Authentication auth) {
		this.applicationEventPublisher
			.publishEvent(new SessionFixationProtectionEvent(auth, originalSessionId, newSession.getId()));
	}

	/**
	 * Sets the {@link ApplicationEventPublisher} to use for submitting
	 * {@link SessionFixationProtectionEvent}. The default is to not submit the
	 * {@link SessionFixationProtectionEvent}.
	 * @param applicationEventPublisher the {@link ApplicationEventPublisher}. Cannot be
	 * null.
	 */
	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		Assert.notNull(applicationEventPublisher, "applicationEventPublisher cannot be null");
		this.applicationEventPublisher = applicationEventPublisher;
	}

	public void setAlwaysCreateSession(boolean alwaysCreateSession) {
		this.alwaysCreateSession = alwaysCreateSession;
	}

	protected static final class NullEventPublisher implements ApplicationEventPublisher {

		@Override
		public void publishEvent(ApplicationEvent event) {
		}

		@Override
		public void publishEvent(Object event) {
		}

	}

}
